import { useState } from 'react';
import { Text, View, Input, Button, Image } from "@tarojs/components";
import Taro, {useLoad} from '@tarojs/taro'
import './index.scss'
import {postRequest} from "../../util/request";

export default function Index() {

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  useLoad(() => {
    console.log('登录页面加载')
  })

  const handleLogin = () => {
    postRequest('/token/apply', { username, password }, (res) => {
      if (res.success) {
        Taro.setStorageSync('token', res.data.token);
        Taro.setStorageSync('realname', res.data.realname);
        Taro.setStorageSync('userId', res.data.id);
        Taro.setStorageSync('userPermission', res.data.role?.permission);
        Taro.switchTab({url: `/pages/index/index`});
      } else {
        Taro.showToast({title: res.message, icon: 'none'})
      }
    })
  };

  return (
    <View className='login-page'>
      <Image src='http://120.77.156.204:8087/sinpo/file/images/bg1.jpg' className='bg-img' />
      <Text className='login-title'>团 练 宝</Text>
      <View className='input-container'>
        <Input
          type='text'
          placeholder='用户名'
          value={username}
          onInput={e => setUsername(e.detail.value)}
          className='login-input'
        />
        <Input
          type='text'
          placeholder='密码'
          password
          value={password}
          onInput={e => setPassword(e.detail.value)}
          className='login-input'
        />
      </View>
      <Button className='login-button' onClick={handleLogin}>登 录</Button>
    </View>
  );
}
